<template>
  <view class="container">
    <!-- 动态新闻类型导航 -->
    <view class="nav-bar">
      <text 
        class="nav-item" 
        v-for="(type, idx) in newsTypes" 
        :key="idx"
        @tap="switchType(type)"
      >{{type}}</text>
    </view>

    <!-- 定期更新的天气+搜索栏 -->
    <view class="weather-search-bar">
      <text class="weather-info">{{weatherInfo}}</text>
      <view class="search-box">
        <input 
          type="text" 
          v-model="searchKey" 
          @input="filterNews" 
          placeholder="搜索关键词"
        />
      </view>
    </view>

    <!-- 下拉刷新提示条 -->
    <view class="update-tip" v-show="showUpdateTip">
      为您更新了{{updateCount}}条内容
    </view>

    <!-- 新闻列表（添加点击跳转事件） -->
    <scroll-view 
      class="news-scroll" 
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      @refresherrefresh="onRefresh"
      :refresher-triggered="isRefreshing"
      refresher-threshold="100"
    >
      <view 
        v-for="(card, index) in filteredList" 
        :key="card._id || `item-${index}`" 
        class="card-item"
        @click="card.cardType !== 'ad' && goToDetail(card._id)" 
      >
        <CardViewText 
          v-bind="card"
        />
      </view>

      <!-- 加载更多提示 -->
      <view class="load-tip" v-if="isLoading">加载中...</view>
      <view class="load-tip" v-if="!isLoading && !hasMore">没有更多内容了</view>
    </scroll-view>

    <!-- 底部Tab栏（可选，如需启用请取消注释并补充样式） -->
    <!-- <view class="tab-bar">
      <view class="tab-item active">首页</view>
      <view class="tab-item">视频</view>
      <view class="tab-item">话题</view>
      <view class="tab-item">我的</view>
    </view> -->
  </view>
</template>

<script>
// 修正JSON路径：uni-app中@代表项目根目录
import news from "@/data/news.json" 
import CardViewText from '@/components/cardViewText.vue'

export default {
  components: {
    CardViewText
  },
  data() {
    return {
      newsTypes: news.types || ["要闻","推荐","关注流","24小时","娱乐","泉州","财经"],
      weatherInfo: '4℃ 小雨 泉州 PM2.59',
      searchKey: '',
      allList: [...news.cardList], // 存储所有新闻（含下拉新增数据）
      page: 1, 
      pageSize: 8, 
      isLoading: false,
      hasMore: true, 
      timer: null,
      updateCount: 0,
      showUpdateTip: false,
      isRefreshing: false, // 下拉刷新状态控制
      activeTab: 'news'
    }
  },
  computed: {
    // 原始完整列表（基于可修改的allList）
    originalList() {
      return this.allList || []
    },
    // 分页后的列表
    paginatedList() {
      const start = (this.page - 1) * this.pageSize
      const end = this.page * this.pageSize
      let list = this.originalList.slice(start, end)

      // 置顶内容前置
      const topList = list.filter(item => item.isTop)
      const normalList = list.filter(item => !item.isTop)
      list = [...topList, ...normalList]

      // 动态插入广告（补充广告卡片缺失的基础字段，避免组件报错）
      if (list.length > 2 && Math.random() > 0.5) {
        const ad = {
          _id: `ad_${Date.now()}_${Math.random()}`,
          title: "我主良缘文化 - 专注婚恋服务",
          author: "广告推广",
          comments: 0,
          time: "",
          cardType: "ad",
          adTag: "广告",
          adInfo: "我主良缘文化",
          images: ["https://picsum.photos/200/150","https://picsum.photos/200/150"],
          isTop: false
        }
        const adIndex = Math.floor(Math.random() * (list.length - 2)) + 1
        list.splice(adIndex, 0, ad)
      }

      return list
    },
    // 搜索过滤后的列表
    filteredList() {
      const key = this.searchKey.trim().toLowerCase()
      let list = this.paginatedList

      if (key) {
        list = list.filter(item => 
          (item.title && item.title.toLowerCase().includes(key)) || 
          (item.author && item.author.toLowerCase().includes(key))
        )
      }

      return list
    }
  },
  onLoad() {
    this.updateWeather()
    // 每30分钟更新一次天气（1800000毫秒）
    this.timer = setInterval(() => this.updateWeather(), 1800000)
  },
  onUnload() {
    // 页面销毁时清除定时器，避免内存泄漏
    clearInterval(this.timer)
  },
  methods: {
    // 跳转到新闻详情页（需提前创建/pages/demos/news/newDetail/newDetail.vue）
    goToDetail(newsId) {
      if (!newsId) return
      uni.navigateTo({
        url: `/pages/demos/news/newDetail/newDetail?id=${newsId}`
      })
    },

    // 下拉刷新核心逻辑（新增单条数据）
    onRefresh() {
      this.isRefreshing = true

      // 模拟生成最新数据
      const newNews = {
        _id: `news_${Date.now()}`,
        title: `实时更新：${new Date().toLocaleTimeString()} 泉州本地最新动态`,
        author: "泉州晚报",
        comments: Math.floor(Math.random() * 100),
        time: "刚刚",
        isTop: false,
        cardType: "text",
        image: "https://picsum.photos/400/200", 
        content: `${new Date().toLocaleTimeString()}更新的泉州本地新闻：今日泉州湾跨海大桥通行效率提升，相关部门优化了车流引导方案，缓解了早晚高峰拥堵问题。`,
        authorAvatar: "/static/avatar/default.png",
        commentsList: [
          { id: 1, user: "泉州网友", content: "终于不堵车了！", like: 7, time: "2分钟前" },
          { id: 2, user: "通勤族", content: "实测有效，点赞！", like: 12, time: "1分钟前" }
        ]
      }

      // 新增数据插入列表最前面
      this.allList = [newNews, ...this.allList]
      this.updateCount = 1 
      this.showUpdateTip = true
      this.page = 1 

      // 3秒后隐藏更新提示
      setTimeout(() => {
        this.showUpdateTip = false
      }, 3000)

      // 结束下拉刷新动画
      setTimeout(() => {
        this.isRefreshing = false
      }, 1000)
    },
    // 上拉加载更多
    loadMore() {
      if (this.isLoading || !this.hasMore) return

      this.isLoading = true
      setTimeout(() => {
        const totalData = this.allList.length
        const currentMax = this.page * this.pageSize

        // 判断是否还有更多数据
        if (currentMax >= totalData) {
          this.hasMore = false
        } else {
          this.page += 1
        }
        this.isLoading = false
      }, 1000)
    },
    // 更新天气（替换为真实接口）
    updateWeather() {
      // 示例接口，需替换为真实的天气API（如和风天气、高德地图等）
      uni.request({
        url: 'https://api.example.com/weather?city=泉州',
        method: 'GET',
        success: (res) => {
          if (res.data && res.data.code === 200) {
            this.weatherInfo = `${res.data.temp}℃ ${res.data.weather} 泉州 PM2.5${res.data.pm25}`
          }
        },
        fail: () => {
          // 接口请求失败时保留原天气信息
          console.log("天气接口请求失败")
        }
      })
    },
    // 搜索过滤（可扩展更复杂的过滤逻辑）
    filterNews() {},
    // 切换新闻类型（可扩展按类型过滤数据）
    switchType(type) {
      this.page = 1
      // 可扩展：根据type过滤allList数据
      // this.allList = news.cardList.filter(item => item.type === type)
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20rpx;
}

/* 导航栏 */
.nav-bar {
  background-color: #d32f2f;
  display: flex;
  padding: 15rpx 20rpx;
  overflow-x: auto;
  white-space: nowrap;
  /* 隐藏滚动条 */
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.nav-bar::-webkit-scrollbar {
  display: none;
}
.nav-item {
  color: #fff;
  font-size: 28rpx;
  margin-right: 30rpx;
  padding: 5rpx 0;
}
.nav-item:active {
  border-bottom: 2rpx solid #fff;
}

/* 天气+搜索栏 */
.weather-search-bar {
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 20rpx;
}
.weather-info {
  font-size: 26rpx;
  color: #333;
}
.search-box {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 8rpx 15rpx;
  font-size: 26rpx;
  color: #999;
  width: 300rpx;
}
.search-box input {
  width: 100%;
  font-size: 26rpx;
  outline: none;
  border: none;
}

/* 更新提示条 */
.update-tip {
  background-color: #ff9800;
  color: #fff;
  font-size: 26rpx;
  padding: 10rpx 20rpx;
  margin: 10rpx 0;
  text-align: center;
}

/* 滚动列表容器 */
.news-scroll {
  height: calc(100vh - 200rpx); /* 适配屏幕高度 */
  padding: 0 10rpx;
}

/* 新闻卡片容器（点击反馈） */
.card-item {
  background-color: #fff;
  margin-bottom: 10rpx;
  box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
  border-radius: 12rpx;
  overflow: hidden;
}
.card-item:active {
  background-color: #f9f9f9;
}

/* 加载提示 */
.load-tip {
  text-align: center;
  padding: 20rpx;
  font-size: 26rpx;
  color: #999;
}

/* 底部Tab栏样式（可选） */
/* .tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  padding: 15rpx 0;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
}
.tab-item {
  font-size: 26rpx;
  color: #999;
}
.tab-item.active {
  color: #d32f2f;
  font-weight: bold;
} */
</style>